<template>
  <div class="login-container">
    <div class="login-box">
      <h2>{{ isLogin ? '登录' : '注册' }}</h2>

      <form @submit.prevent="handleSubmit">
        <div class="form-group">
          <input
              type="text"
              v-model="currentForm.username"
              placeholder="用户名"
              required
          />
        </div>

        <div class="form-group">
          <input
              type="password"
              v-model="currentForm.password"
              placeholder="密码"
              required
          />
        </div>

        <div class="form-group" v-if="!isLogin">
          <input
              type="password"
              v-model="currentForm.rePassword"
              placeholder="确认密码"
              required
          />
        </div>

        <div class="form-group" v-if="!isLogin">
          <input
              type="tel"
              v-model="currentForm.phone"
              placeholder="手机号"
              required
          />
        </div>

        <div class="error-message" v-if="isLogin && loginError">
          {{ loginError }}
        </div>

        <div class="error-message" v-if="!isLogin && registerError">
          {{ registerError }}
        </div>

        <button type="submit" :disabled="loading">
          {{ loading ? '处理中...' : (isLogin ? '登录' : '注册') }}
        </button>

        <p class="switch-mode" @click="toggleMode">
          {{ isLogin ? '没有账号？立即注册' : '已有账号？立即登录' }}
        </p >
      </form>
    </div>
  </div>

  <!-- 消息提示弹窗 -->
  <el-dialog :visible.sync="dialogVisible" title="提示" @close="dialogVisible = false">
    <span>{{ dialogMessage }}</span>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关闭</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import qs from 'qs';

const router = useRouter();
const isLogin = ref(true);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogMessage = ref('');
const loginError = ref('');
const registerError = ref('');

const user_login = ref({
  username: '',
  password: ''
});

const user_registration = ref({
  username: '',
  password: '',
  rePassword: '',
  phone: ''
});

const currentForm = computed(() => (isLogin.value ? user_login.value : user_registration.value));

const toggleMode = () => {
  isLogin.value = !isLogin.value;
  resetForm();
};

const resetForm = () => {
  user_login.value = { username: '', password: '' };
  user_registration.value = { username: '', password: '', rePassword: '', phone: '' };
};

const handleSubmit = async () => {
  if (loading.value) return;

  if (!isLogin.value && currentForm.value.password !== currentForm.value.rePassword) {
    registerError.value = '两次输入的密码不一致';
    return;
  }

  loading.value = true;
  try {
    if (isLogin.value) {
      await login();
    } else {
      await registration();
    }
  } finally {
    loading.value = false;
  }
};

const showDialog = (message) => {
  dialogMessage.value = message;
  dialogVisible.value = true;
};

const login = async () => {
  try {
    loginError.value = '';
    const response = await axios.post(`${BASE_URL}/v1/user/login`, currentForm.value);
    if (response.data.code === 2000) {
      showDialog('登录成功!');
      const userData = {
        ...response.data.data,
        email: response.data.data.email || '',
        memberLevel: response.data.data.memberLevel || '普通会员'
      };
      localStorage.setItem('user', JSON.stringify(userData));
      localStorage.setItem('token', response.data.data.token);
      router.push('/');
    } else {
      loginError.value = response.data.msg || '登录失败';
      resetForm();
    }
  } catch (error) {
    loginError.value = error.response?.data?.msg || '登录失败，请稍后再试';
    console.error(error);
  }
};

const registration = async () => {
  try {
    registerError.value = '';
    const data = qs.stringify(currentForm.value);
    const response = await axios.post(`${BASE_URL}/v1/user/save`, data);
    if (response.data.code === 2000) {
      showDialog('注册成功，请登录');
      toggleMode();
    } else {
      registerError.value = response.data.msg || '注册失败';
    }
  } catch (error) {
    registerError.value = error.response?.data?.msg || '注册失败，请稍后再试';
    console.error(error);
  }
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
}

.login-box {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

button {
  width: 100%;
  padding: 12px;
  background: #ff5f16;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

button:disabled {
  background: #ffaa83;
  cursor: not-allowed;
}

.switch-mode {
  text-align: center;
  margin-top: 20px;
  color: #666;
  cursor: pointer;
}

.switch-mode:hover {
  color: #ff5f16;
}

.error-message {
  color: #ff4444;
  font-size: 14px;
  margin-bottom: 15px;
  text-align: center;
}
</style>